﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Collections;
using System.Threading;
using HammerMUD.System;

namespace HammerMUDServer
{
    public class Connection
    {
        private static object BigLock = new object();
        private User user;
        HammerMUD.System.HammerMUD hammerMUD;
        
        public Connection(Socket socket, HammerMUD.System.HammerMUD hammerMUD)
        {
            StreamReader reader;
            StreamWriter writer;

            this.hammerMUD = hammerMUD;

            Console.WriteLine("Client connected..");

            reader = new StreamReader(new NetworkStream(socket, false));
            writer = new StreamWriter(new NetworkStream(socket, true));

            user = new User(writer, reader, socket);
            new Thread(ClientLoop).Start();
        }

        void ClientLoop()
        {
            try
            {
                lock (BigLock)
                {
                    hammerMUD.OnConnect(user);
                }

                while (true)
                {
                    lock (BigLock)
                    {
                        hammerMUD.FlushUsers();
                    }
                    string line = user.Read();
                    if (line == null)
                    {
                        break;
                    }
                    lock (BigLock)
                    {
                        hammerMUD.ProcessLine(line, user);
                    }
                }
            }
            finally
            {
                lock (BigLock)
                {
                    hammerMUD.Disconnect(user);
                }
            }
        }
    }
}
